package com.fpx.order.plat.bussiness.plat.amazon.service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fpx.api.bean.order.Order;
import com.fpx.api.bean.order.OrderItem;
import com.fpx.api.bean.request.GetOrderRequest;
import com.fpx.api.bean.response.GetOrderResponse;
import com.fpx.api.service.IAmazonService;
import com.fpx.order.plat.bussiness.cache.CacheManage;
import com.fpx.order.plat.bussiness.entity.CustomerShop;
import com.fpx.order.plat.bussiness.entity.OriginOrder;
import com.fpx.order.plat.bussiness.entity.OriginOrderAddress;
import com.fpx.order.plat.bussiness.entity.OriginOrderitem;
import com.fpx.order.plat.bussiness.entity.PullOrderLog;
import com.fpx.order.plat.bussiness.plat.base.IPlatOrderHandler;
import com.fpx.order.plat.bussiness.plat.base.SdkCommonRequestOrderThread;
import com.fpx.order.plat.bussiness.service.log.IPullOrderLogService;
import com.fpx.order.plat.bussiness.service.order.IOriginOrderService;
import com.fpx.order.plat.bussiness.system.CacheConstants;
import com.fpx.order.plat.bussiness.system.PlatConstants;
import com.fpx.order.plat.bussiness.vo.OrderDealResult;
import com.fpx.order.plat.common.utils.DateFormatUtils;
import com.fpx.order.plat.common.utils.DecimalUtils;

/**
 * desc: 亚马逊拉单平台
 * @author xiangtao(xiangtao@4px.com)
 * @date 2015年11月24日 下午3:33:16
 * @version 1.0
 */
@Component
public class AmazonPlatOrderHandler implements IPlatOrderHandler {	

	private final static Logger LOGGER = Logger.getLogger(AmazonPlatOrderHandler.class);
	
	@Autowired
	private IPullOrderLogService pullOrderLogService;
	@Autowired
	private IOriginOrderService originOrderService;
	@Autowired
	private IAmazonService amazonService;
	@Autowired 
	private CacheManage cacheManage;
	
	@Override
	public List<OrderDealResult> getOrderByCustomer(CustomerShop customer, String startTime, String endTime,
			int isAt) throws Exception {
		//结果
        List<OrderDealResult> orderDealRs = new ArrayList<OrderDealResult>();
        //商家编号
        String cm_id = customer.getCm_id();
        //商家ID
        String cs_id = customer.getCs_id();
        //授权码
        String accessToken = customer.getCs_token();
        
        if(StringUtils.isEmpty(cm_id)){
			LOGGER.info("【AMAZON】---该商家不存在 或 cm_id 为空!");
        	throw new RuntimeException("【AMAZON】---该商家不存在 或 cm_id 为空!");
		}
		if(StringUtils.isEmpty(cs_id)){
			LOGGER.info("【AMAZON】---商家：[" + cm_id + "]- 当前商铺不存在 或cs_id为空!");
        	throw new RuntimeException("【AMAZON】---商家：[" + cm_id + "]- 当前商铺不存在 或cs_id为空!");
		}	
        if (!StringUtils.isNotEmpty(accessToken)) {
        	LOGGER.info("【AMAZON】---商家：[" + cm_id + "]-商铺ID:["+cs_id+"],accessToken为空!");
            return orderDealRs;     
        }
        String reqStartTime = null ;
        String reqEndTime = null ;
        PullOrderLog synTime = null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      //判断拉单类型 0自动拉单 1手动
        if(isAt==0){
        	 //根据店铺与同步类型获取获取最后同步时间
        	synTime = pullOrderLogService.findLastSyncTime(cm_id, cs_id, PlatConstants.ORDER_SOURCE_AM);
            if (null == synTime) {
            	//拉单开始时间提前60分钟
            	reqStartTime = df.format(DateFormatUtils.getCalendarDateTime(60));
            	//拉单结束时间推后30分钟
            	reqEndTime = df.format(DateFormatUtils.getCalendarDateTime(4));
            } else {
            	//请求时间提前30分钟
            	reqStartTime = df.format(DateFormatUtils.getMoveAfterDate("yyyy-MM-dd HH:mm:ss",synTime.getPull_date_end(), -30));
            	reqEndTime = df.format(DateFormatUtils.getCalendarDateTime(4));
            	//时间跨度不能超过20天,设置时间
                Calendar cal = Calendar.getInstance();
                cal.setTime(df.parse(reqEndTime));
                cal.add(Calendar.DATE, -20);
                Date miniStartDate = cal.getTime();
                if(df.parse(reqStartTime).getTime() < miniStartDate.getTime()){
                	reqStartTime = df.format(miniStartDate);
                }
            }
        }else if(isAt == 1){
        	reqStartTime = startTime;
        	reqEndTime = endTime;
        }
        Date reqStartD=reqStartTime!=null?
        		df.parse(reqStartTime):DateFormatUtils.getCalendarDateTime(60);
        Date reqEndD=reqEndTime!=null?df.parse(reqEndTime):DateFormatUtils.getCalendarDateTime(4);	
        //请求订单数据
        GetOrderResponse repData = request(customer,reqStartD, reqEndD);
        if(repData==null){
        	return orderDealRs; 
        }
        //解析订单数据
        List<OriginOrder> orderList = analysisResponse(customer, repData);
        for(OriginOrder originOrder:orderList){
        	String orderCode=originOrder.getOrder_code();
    		try{
    			originOrderService.save(originOrder);
    			orderDealRs.add(new OrderDealResult("0","成功",orderCode));
    			LOGGER.info("【AMAZON】---商家：[" + cm_id + "]-商铺ID:["+cs_id+"]-订单号:["+orderCode+"]---保存成功！");
    		}catch(Exception e){
    			LOGGER.error("【AMAZON】---商家：[" + cm_id + "]-商铺ID:["+cs_id+"]-订单号:["+orderCode+"]---异常信息:["+e.getMessage()+"]");
    			orderDealRs.add(new OrderDealResult("1",e.getMessage(),originOrder.getRef_code()));
    		}
    	}
		return orderDealRs;
	}

	public GetOrderResponse request(CustomerShop customer,Date startDate, Date endDate) throws Exception{
		//商铺ID
        String csid = customer.getCs_id();
        //客户号
        String cmid=customer.getCm_id();
      //授权码
        String accessToken = customer.getCs_token();
        //时间跨度不能超过10天,设置时间
        Calendar cal = Calendar.getInstance();
        cal.setTime(endDate);
        cal.add(Calendar.DATE, -10);
        Date miniStartDate = cal.getTime();
        if(startDate.getTime() < miniStartDate.getTime()){
        	startDate = miniStartDate;
        }
		//request参数封装
		GetOrderRequest request = new GetOrderRequest();
		Map<String,String>configMap=
				cacheManage.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_AMAZON);
		request.setConfigMap(configMap);
		//平台类型   Amazon
		request.setPlatform(com.fpx.api.util.Constant.PLATFORM_AMAZON);
		request.setToken(accessToken);
		//站点
		request.setSite(customer.getCs_site());
		//订单的起始时间
		request.setStartDate(startDate);
		//订单的结束时间
		request.setEndDate(endDate);
		//返回结果
		SdkCommonRequestOrderThread requestThread = new SdkCommonRequestOrderThread(request,PlatConstants.ORDER_SOURCE_AM,amazonService);
		new Thread(requestThread).start();
		GetOrderResponse response = requestThread.getResponse();
		if(response==null){
			LOGGER.info("【amazon】拉单请求【超时】,商家:【" + cmid + "】商铺ID:【"+csid+"】");
			return null;
		}
		return response;
	}
//	
	public List<OriginOrder> analysisResponse(CustomerShop customer,GetOrderResponse response) throws Exception{
		List<OriginOrder> orderRs = new ArrayList<OriginOrder>();
		String ack = response.getAck();
		if(ack.equals(com.fpx.api.util.Constant.ACK_SUCCESS)){
			List<Order> platOrderList = response.getOrders();
			for(Order platOrder:platOrderList){
				OriginOrder sales = new OriginOrder();
				OriginOrderAddress orderAddress=new OriginOrderAddress();
				//单据来源
				sales.setPlatform_code(PlatConstants.ORDER_SOURCE_AM);//1
				//订单号
				sales.setOrder_code(platOrder.getOrderNo());//2
				//参考单号
				sales.setRef_code(platOrder.getOrderNo());//3
				//上传服务商跟踪号(N:未上传;U:上传中;Y:上传成功)
				sales.setUpload_ship_code(PlatConstants.UPLOAD_STATUS_N);//N:未上传 4
				//付款时间 
				Date paidTime = platOrder.getPaidTime();
				if(null != paidTime){
					sales.setPayment_time(paidTime);//5
				}
				// 付款方式=“银行汇款”
				sales.setPayment_method(PlatConstants.PAYMENTMETHOD);//6
				
				// 客户id
				sales.setCustomer_id(customer.getCm_id());//7
				//客户名下的店铺账号  对应的商铺代码
				sales.setShop_account(customer.getCs_code());//8
				// 买家昵称
				sales.setBuyer_id(platOrder.getBuyerId());//9
				
				// 平台物流配送方式(Amazon 暂时不做渠道映射)
//				sales.setShipping_service(platOrder.getShippingService());//10
				
				// 运输成本
				Double transportSum = platOrder.getShippingServiceCost();
				if(transportSum!=null){
					sales.setShipping_service_cost(transportSum + "");//11
				}
				
				// 交易站点ID
				sales.setTransaction_site_id(platOrder.getTransactionSiteId());//12
				// 单据状态 :待处理 状态
				sales.setPfo_os_code(PlatConstants.ORDER_STATUS_NEW);// 13
				
				if (StringUtils.isNotEmpty(platOrder.getNote())) {
					sales.setRemark(platOrder.getNote());//14
				}
				//创建时间
				sales.setPfo_createdate(new Date());//15
				//最后修改时间
				sales.setPfo_modifydate(new Date());//16
				
				/**
				 * 收人地址信息
				 */
				// 收件人姓名
				orderAddress.setConsignee_name(platOrder.getConsigneeName());
				// 收件人街道1
				orderAddress.setConsignee_street1(StringUtils.isEmpty(platOrder
						.getConsigneeAddressLine1()) ? platOrder
						.getConsigneeAddressLine2() : platOrder
						.getConsigneeAddressLine1());
				// 收件人街道2
				orderAddress.setConsignee_street2(platOrder.getConsigneeAddressLine2());
				// 收件人城市
				orderAddress.setConsignee_cityname(platOrder.getConsigneeCity());
				//收件人城市州/省
				orderAddress.setConsignee_stateorprovince(platOrder.getConsigneeState());
				//收件人国家 代码
				orderAddress.setConsignee_country_code(platOrder.getDestinationCountryCode());
				//收件人国家名称
				orderAddress.setConsignee_country_name(platOrder.getDestinationCountryName());
				//收件人邮编
				orderAddress.setConsignee_postcode(platOrder.getConsigneePostCode());
				//收件人电话
				orderAddress.setConsignee_phone(platOrder.getConsigneePhone());
				
				// 总金额
				double totalPrice = 0.0d;

				//订单明细
				List<OriginOrderitem> details = new ArrayList<OriginOrderitem>();
				List<OrderItem> orders = platOrder.getItems();
				for (int j = 0; j < orders.size(); j++) {
					OrderItem orderItem = orders.get(j);
					//保存
					OriginOrderitem originOrderitem = new OriginOrderitem();
					
					 // 货品序列(多个货品从1开始累加)
					originOrderitem.setPfoo_item_seq(DecimalUtils.fomatDecimal(j + 1,"000"));
					
					// 商品ID
					originOrderitem.setItem_code(orderItem.getSku());
					
					// 商品名称
					originOrderitem.setItem_name(orderItem.getItemTitle());
					
					/// 货品数量
					BigDecimal planQty = new BigDecimal(orderItem.getQuantity() == null ? 0 : orderItem.getQuantity());
					originOrderitem.setQuantity(String.valueOf(planQty));
					
					/// 单价(当前销售价格)
					double tprice = DecimalUtils.round(2, orderItem.getPrice() == null ? 0 : orderItem.getPrice());
					BigDecimal price = new BigDecimal(tprice);
					originOrderitem.setCurrent_price(String.valueOf(price));
					
					// 买家实付金额=单价*数量
					BigDecimal paymentSum = price.multiply(planQty);
					double paySum = DecimalUtils.round(2, paymentSum.doubleValue());
					originOrderitem.setPayment_sum(String.valueOf(paySum));
					
					//交易ID
					originOrderitem.setTransaction_id(orderItem.getSku());
					
					// 货品标识码=子订单号
					originOrderitem.setItem_id(orderItem.getItemId());
					
					// 币种
					originOrderitem.setCurrency(platOrder.getCurrency());
					
					totalPrice += paySum;// 累计总金额
	
					details.add(originOrderitem);
				}
				//支付总金额
				sales.setAmount_paid(String.valueOf(DecimalUtils.round(2, totalPrice)));
				sales.setOrderAddress(orderAddress);
				sales.setOrderitems(details);
				orderRs.add(sales);
			}
		}else{
			String failMessage = response.getFailMessage();
			if(failMessage==null){
				failMessage = "null值错误";
			}
			throw new Exception(failMessage);
		}
		return orderRs;
	}

}
